package org.kwisatz.proxybot.core;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import org.kwisatz.proxybot.Main;


public class Pipe extends Thread
{
	public interface Filter
	{
		String handleLine(String line);
	}

	private static final Filter VOID_LISTENER=new Filter()
	{
		public String handleLine(String line)
		{
			return line;
		}
	};
	
	private BufferedReader in;
	private PrintWriter out;
	private Filter listener=VOID_LISTENER;

	public Pipe(BufferedReader in, PrintWriter out)
	{
		this.in=in;
		this.out=out;
	}
		
	public void run()
	{
		try
		{
			String line = in.readLine();
			while(line!=null)
			{
				Main.LOGGER.finest("in: "+line);
				line=listener.handleLine(line);
				Main.LOGGER.finest("filtered: "+line);
				if(line!=null)
					out.println(line);
				
				line = in.readLine();
			}
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		closing();
	}
	
	public void setListener(Filter listener)
	{
		this.listener=listener;
	}

	/** overide to set a closing action */
	protected void closing()
	{
		//nothing
	}
}
